package com.outdoor.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import java.util.List;

/**
 * 类型处理器配置类
 */
@Configuration
@ConditionalOnBean(SqlSessionFactory.class)
@DependsOn("mybatisPlusConfig")
public class TypeHandlerConfig implements InitializingBean {

    private final List<SqlSessionFactory> sqlSessionFactoryList;
    private final ApplicationContext applicationContext;
    
    public TypeHandlerConfig(List<SqlSessionFactory> sqlSessionFactoryList, ApplicationContext applicationContext) {
        this.sqlSessionFactoryList = sqlSessionFactoryList;
        this.applicationContext = applicationContext;
    }
    
    @Override
    public void afterPropertiesSet() {
        // 确保所有Bean初始化完成后再执行
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
            TypeHandlerRegistry typeHandlerRegistry = sqlSessionFactory.getConfiguration().getTypeHandlerRegistry();
            // 动态获取类，避免直接引用造成的编译问题
            try {
                Class<?> handlerClass = Class.forName("com.outdoor.handler.JsonTypeHandler");
                Class<?> targetClass = List.class;
                // 注册类型处理器
                typeHandlerRegistry.register(targetClass, handlerClass);
            } catch (ClassNotFoundException e) {
                System.err.println("未找到JsonTypeHandler类: " + e.getMessage());
            }
        }
    }
} 